package com.huayanginfo.saas.member;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;

import com.huayanginfo.saas.directory.LDAPService;
import com.huayanginfo.saas.domain.member.User;
import com.huayanginfo.saas.support.BaseAction;
import com.huayanginfo.saas.support.Security;
import com.opensymphony.xwork2.ModelDriven;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class LoginAction extends BaseAction implements ModelDriven<User> {

	private static final long serialVersionUID = 3170917054103860557L;

	public String execute() throws Exception {

		String email = getUser().getEmail();;
		
		String userDN = LDAPService.getUserDN(email);
		
		if (userDN == null) {
			addActionError("User not exist");
			return LOGIN;
		}

		if (!LDAPService.validateDN(userDN, user.getPassword())) {
			addActionError("Invalid User name or password");
			return LOGIN;
		}
		
		
		if (remember) {
			byte[] encoded = Security.symmetryEncrypt(email.getBytes("UTF-8"));
			Cookie cookie = new Cookie("el",Base64.encode(encoded));
			//默认3个月有效期
			cookie.setMaxAge(7776000);
			ServletActionContext.getResponse().addCookie(cookie);
		}

		LoginService.doLoginWork(email, userDN, getApplication(), getSession());
		
		return SUCCESS;
	}
	
	private User user = new User();

	public User getUser() {
		return user;
	}

	private boolean remember;

	public boolean isRemember() {
		return remember;
	}

	public void setRemember(boolean remember) {
		this.remember = remember;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public User getModel() {
		return getUser();
	}

}
